package com.fnn.util;


import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 图片验证码
 */
@WebServlet("/captcha")
public class CaptchaUtil extends HttpServlet {
    private static final long serialVersionUID=1L;

    //生成指定长度的验证码
    public String getCaptcha(int size){
        String captcha="";
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        for(int i=0;i<size;i++){
            char c=str.charAt(random.nextInt(str.length()));
            captcha=captcha+c;
        }
        return captcha;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        int width=100;
        int height=30;
        Random random=new Random();

        //创建空白图片，宽100，高30像素，rgb颜色
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //获取图片画笔
        Graphics graphics=image.getGraphics();
        //设置画笔颜色
        graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
        //绘制矩形
        graphics.fillRect(0,0,width,height);
        //绘制8条干扰线
        for(int i=0;i<8;i++){
            //设置画笔颜色
            graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            //划线，前两个参数是第一个点的xy坐标，后两个参数是第二个点的xy坐标
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }

        //调用方法，获取验证码
        String captcha=getCaptcha(4);

        HttpSession session = req.getSession();
        session.setAttribute("captcha_picture",captcha);

        //设置字体，样式倾斜、加粗，25榜大小
        graphics.setFont(new Font(null,Font.ITALIC+Font.BOLD,25));
        //将字符串画在指定坐标上
        graphics.drawString(captcha,15,25);
        System.out.println(captcha);
        //设置响应格式
        resp.setContentType("image/jpeg");
        //以流的形式响应
        OutputStream outputStream=resp.getOutputStream();
        //把此图片写入到输出流里，jpeg格式
        ImageIO.write(image,"jpeg",outputStream);
        //关闭流
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

